package com.jlz.managers.core;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jlz.beans.core.CategoryBean;
import com.jlz.beans.def.ColumnBean;
import com.jlz.managers.def.Columns;
import com.julewa.Client;
import com.julewa.db.Store;

@Service("Categories") 
public class Categories {
	
	private Store<CategoryBean> store = new Store<CategoryBean>(CategoryBean.class);
	@Autowired Client client;
	private @Autowired Columns columns;
	@SuppressWarnings("unused")
	@PostConstruct
	private void init(){
		List<CategoryBean> ls = this.getAll();
		if(!ls.isEmpty())return;
		append(create("house", "住宅"));
		append(create("shop",  "商铺"));
		append(create("office","写字楼"));
		append(create("factory","厂房"));
		append(create("carrier", "货车"));
		append(create("engine",  "工程车"));
	}
	
	public CategoryBean create(String code, String label){
		CategoryBean c = store.create();
		c.setLabel(label);
		c.setCode(code);
		return c;
	}
	
	public CategoryBean create(){
		return store.create();
	}
	
	private long _create_column_(CategoryBean category, String code, int idx){
		ColumnBean col = columns.create(code);
		col.setParentId( - category.getID());
		col.setIdx(idx);
		columns.insert(col);
		return col.getID();
	}
	
	public boolean append(CategoryBean category){
		category.setID(store.generateID());
		if(category.getAssetColumnRoot() < 0){    
			category.setAssetColumnRoot(_create_column_(category, "assert", 1));
		}
		if(category.getDesireColumnRoot() < 0){    
			category.setDesireColumnRoot(_create_column_(category, "desire", 2));
		}
		if(category.getContractColumnRoot() < 0){    
			category.setContractColumnRoot(_create_column_(category, "contract", 3));
		}
		return store.insert(category);
	}
	
	public boolean update(CategoryBean category){
		return store.update(category);
	}
	
	public boolean remove(CategoryBean category){
		return store.delete(category);
	}
	
	public CategoryBean get(long categoryid){
		return store.get(categoryid);
	}
	
	public List<CategoryBean> getAll(){
		return store.select("all",null);
	}
	
	public List<CategoryBean> getMenu(){
		return getAll();
	}
	
	private static final String KEY_CURRENT_CATEGORY = Categories.class.getCanonicalName();
	public CategoryBean getCurrentCategory(){
		CategoryBean c = (CategoryBean)client.getSession(KEY_CURRENT_CATEGORY);
		if(c == null)return this.getAll().get(0);
		return c;
	}

	public void setCurrentCategory(Long id) {
		if(id == null){
			client.setSession(KEY_CURRENT_CATEGORY, null);
		}else{
			client.setSession(KEY_CURRENT_CATEGORY, this.get(id));
		}
	}

}
